<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级id" prop="claId">
        <el-input
          v-model="queryParams.claId"
          placeholder="请输入班级id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上课日期" prop="claDate">
        <el-date-picker clearable
          v-model="queryParams.claDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择上课日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上课教学楼" prop="roomName">
        <el-input
          v-model="queryParams.roomName"
          placeholder="请输入上课教学楼"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程" prop="course">
        <el-input
          v-model="queryParams.course"
          placeholder="请输入课程"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上课开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择上课开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="timeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上课日期" align="center" prop="claDate" width="180">
        <template slot-scope="scope">
          <span >{{ scope.row.claDate }} {{ scope.row.startTime.substr(0,5) }}~{{ scope.row.endTime.substr(0,5) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级名" align="center" prop="claName" />

      <el-table-column label="教师" align="center" prop="name" />
      <el-table-column label="上课教室号" align="center" prop="roomId" />
      <el-table-column label="上课教学楼" align="center" prop="roomName" />
      <el-table-column align="center" prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '1'" type="danger">待上课</el-tag>
          <el-tag v-else-if="scope.row.status === '2'">已上课</el-tag>
          <el-tag v-else-if="scope.row.status === '3'" type="warning" style="font-size: 14px;"> 延 课 </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="课程" align="center" prop="course" />


      <el-table-column label="课时消耗" align="center" prop="payTotalHour" />
      <el-table-column label="到课人数" align="center" prop="atClassCnt" />
      <el-table-column label="请假人数" align="center" prop="leaveCnt" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">



          <el-button
            v-if="scope.row.status === '1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleClassUpdate(scope.row)"
            v-hasPermi="['system:time:edit']"
          >点名</el-button>
          <el-button
            v-if="scope.row.status === '2'"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleUpdateHadAttend(scope.row)"
          >修改点名</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:time:edit']"
          >调课</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:time:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改排课信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="cancel" width="600px">
      <el-form ref="form" v-loading="loadingChange" class="add-form auto-width" :model="form" :rules="rules" label-width="90px">
        <el-row v-if="form.courseTimeId !== undefined && form.courseTimeId !== ''">
          <el-col :span="12">
            <el-form-item label="班级:">
              <el-input :value="form.claName" readonly disabled size="small" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上课日期:" prop="claDate" >
              <el-date-picker
                v-model="form.claDate"
                clearable
                size="small"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择上课日期"
                :picker-options="beginDatePickerOptions"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>


          <el-col :span="12">
            <el-form-item label="教学楼:" prop="roomId">
              <el-input v-model="form.roomId"  placeholder="请选择教学楼" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教室:" prop="roomId">
              <el-input v-model="form.roomName"  placeholder="请选择教室" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上课时间:" prop="startTime" :key="form.startTime">
              <el-time-select
                v-model="form.startTime"
                size="small"
                :picker-options="{
                start: '08:00',
                step: '00:30',
                end: '19:00'
              }"
                placeholder="选择上课时间"
              />
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="下课时间:" prop="endTime" :key="form.endTime">
              <el-time-select
                v-model="form.endTime"
                size="small"
                :picker-options="{
                start: '08:00',
                step: '00:30',
                end: '20:00'
              }"
                placeholder="选择下课时间"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.courseTimeId !== undefined && form.courseTimeId !== ''" >
          <el-col :span="12">
            <el-form-item label="任课教师:" prop="teacherId">
              <el-input v-model="form.teacherName" teacher="1"  readonly disabled  placeholder="请选择任课教师" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上课主题:" prop="classTheme">
              <el-input v-model="form.course" size="small" readonly disabled placeholder="请输入上课主题" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loadingChange" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>




    <el-dialog :title="'记上课:  ' + claInfo.claName +' '+' '+' '+ '上课时间'+' '+' '+claInfo.claDate+' '+' '+' '+claInfo.startTime+'~'+claInfo.endTime+' '+'  '+'('+'教师：' + claInfo.teacherName + ')'" :visible.sync="opendata" @close="cancel" class="compact" width="850px">
    <el-row :gutter="10" class="mb8" style="margin-top: 10px;">
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-collection"
          size="mini"
          @click="handleAutoDealStudentAttendStatusInfo('1')"
        >全到课</el-button>
        <el-button
          type="info"
          icon="el-icon-switch-button"
          size="mini"
          @click="handleAutoDealStudentAttendStatusInfo('2')"
        >全缺勤</el-button>
        <el-tooltip content="本次不记录上课，不扣减课时，后续重新确认上课时间!" placement="top">
        <el-button
          v-if="delayInfo"
          type="warning"
          icon="el-icon-switch-button"
          size="mini"
          @click="deleteClaTime()"
        >延 课</el-button>
          </el-tooltip>
      </el-col>

    </el-row>
    <el-table ref="table" v-loading="loadingClass" class="add-cla-time-attend-table" :data="dataList" @selection-change="handleSelectionChanges">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="studentName" label="学生" fixed="left" />
      <el-table-column align="center" prop="phone" label="是否到课" width="150" fixed="left">
        <template slot-scope="scope">
          <el-radio-group v-model="studentAttendStatusForm[scope.row.studentCourseId].attendStatus" size="mini" @change="attendStatus => handleAttendStatusChange(attendStatus, scope.row)">
            <el-radio-button
              v-for="dict in attendStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio-button>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column align="center" label="扣减课时" width="90" fixed="left">
        <template slot-scope="scope">
          <el-input-number
            v-model="studentAttendStatusForm[scope.row.studentCourseId].stuLoseHour"
            :disabled="true"
            style="width: 80px"
            controls-position="right"
            :min="0"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="age" label="年龄" fixed="left" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>



      <el-table-column align="center" prop="chargeType" label="剩余课时/总课时" width="150" >
        <template slot-scope="scope">
              <span>{{ scope.row.balanceHour}} / {{scope.row.totalHour }}课时</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="chargeType" label="联系人/联系昵称/联系电话" width="400" >
        <template slot-scope="scope">
          <span v-for ="column in scope.row.contactList">{{ column.contactRelation}} / {{''+column.contactNick+' '+' ' }}{{column.contactPhone }} | </span>
        </template>

      </el-table-column>

    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="dataList.length > 0" :loading="loadingClass" type="primary" @click="handleClaAttend">上 课</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTime, getTime, delTime, addTime, updateTime } from "@/api/system/time";
import { getScStudentCourseClass,getScStudentCourseAttendClass } from "@/api/system/scStudentCourse";
import { addAttend,updateAttend } from "@/api/system/attend";

import moment from 'moment'
export default {
  dicts: ['sys_user_sex'],
  name: "Time",
  data() {
    return {
      dataList:[],
      claInfo:{},
      // 遮罩层
      loading: true,
      title: '调课',
      loadingChange: false,
      loadingClass: false,

      // 延课标志
      delayInfo:false,

      // 到课状态
      attendStatusOptions: [
        {dictValue: '1' ,
          dictLabel: "到课",
        },
        {dictValue: '2',
          dictLabel:"请假",
        }



      ],
      // 每个学生 的到课状态
      studentAttendStatusForm: {},

      // 选中数组
      ids: [],

      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排课信息表格数据
      timeList: [],
      // 弹出层标题
      // 是否显示调课弹出层
      open: false,
      // 是否显示点名弹出层
      opendata: false,
      // 班级
      claOptions:[],
      // 选择上课的学生
      chooseStudentCourseIds: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        claId: null,
        claDate: null,
        roomName: null,
        course: null,
        startTime: null,
      },

      beginDatePickerOptions: {
        disabledDate(time) {
          return moment(time).add(1, 'days').valueOf() < Date.now()
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        claId: [
          { required: true, message: "班级id不能为空", trigger: "blur" }
        ],
        claDate: [
          { required: true, message: "上课日期不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "上课开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "上课结束时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    // this.getClaOptions();
  },
  methods: {

    // /** 选择科目 查询班级 */
    // getClaOptions() {
    //     simpleListCla(this.queryy).then(response => {
    //       this.claOptions = response.data;
    //
    //     })},
    /** 延课 */
    deleteClaTime(){
      this.loadingClass = true
      const query = {}
      query.courseTimeId=this.claInfo.courseTimeId
      query.status="3"
      updateTime(query).then(response => {
        this.$modal.msgSuccess("延课成功");
        this.getList();
        this.loadingClass = false
      }).catch(() => {
        this.loadingClass = false
      })
      this.cancel()
    },
    /** 点名记录 */
    loadClaInfo(claId) {
      if (claId) {
        this.loadingClass = true
        getScStudentCourseClass(claId).then(response => {
          // console.log(response)
          this.dataList=response.data
            this.handleAutoDealStudentAttendStatusInfo('1')
          this.loadingClass = false
        }).catch(() => {
          this.loadingClass = false
        })
      }
    },
    /** 修改点名记录 */
    loadClaAttendInfo(claId,courseTimeId) {
      if (claId) {
        const query={}
        query.claId=claId
        query.courseTimeId=courseTimeId
        this.loadingClass = true
        getScStudentCourseAttendClass(query).then(response => {
          console.log(response)
          this.dataList=response.data
          this.handleAutoDealStudentAttendStatusInfo('3')
          this.loadingClass = false
        }).catch(() => {
          this.loadingClass = false
        })
      }
    },

    afterNow(date) {
      return moment(date).add(1, 'days').toDate().getTime() < new Date().getTime()
    },
    /** 查询排课信息列表 */
    getList() {
      this.loading = true;
      listTime(this.queryParams).then(response => {
        this.timeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.idsAttend=[];
      this.opendata=false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseTimeId: null,
        ruleId: null,
        claId: null,
        claDate: null,
        teacherId: null,
        roomId: null,
        roomName: null,
        course: null,
        startTime: null,
        endTime: null,
        payTotalHour: null,
        atClassCnt: null,
        leaveCnt: null,
        createUser: null,
        createTime: null,
        lastUpdateUser: null,
        lastUpdateTime: null
      };
      this.delayInfo = false,
      this.dataList = []
      this.claInfo = {
        claName: '',
        deptName: '',
        departId: undefined
      }
      this.studentAttendStatusForm = {}
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseTimeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 多选框选中数据
    handleSelectionChanges(selection) {
      this.chooseStudentCourseIds = selection.map(item => item.studentCourseId)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.idsAttend=[];
      this.open = true;
      this.title = "添加排课信息";
    },
    /** 调课按钮操作 */
    handleUpdate(row) {
      this.reset();
      const courseTimeId = row.courseTimeId || this.ids
      getTime(courseTimeId).then(response => {
        this.form = response.data;
        this.form.claName = row.claName
        this.form.teacherName = row.name
        this.open = true;
        this.title = "修改排课信息";
      });
    },
    /** 已上课编辑 */
    handleUpdateHadAttend(row) {
      this.reset();
      const courseTimeId = row.courseTimeId

      getTime(courseTimeId).then(response => {

        this.claInfo = response.data;
        this.claInfo.claName =row.claName
        this.claInfo.teacherName =row.name
        this.claInfo.claDate =row.claDate
        this.claInfo.startTime =row.startTime
        this.claInfo.endTime =row.endTime
        this.claInfo.status =row.status
        this.opendata = true;
        this.loadClaAttendInfo(row.claId,courseTimeId)

      });
    },

      /** 点名按钮操作 */
      handleClassUpdate(row) {
        this.reset();
        this.delayInfo=true
        const courseTimeId = row.courseTimeId
        getTime(courseTimeId).then(response => {

          this.claInfo = response.data;
          this.claInfo.claName =row.claName
          this.claInfo.teacherName =row.name
          this.claInfo.claDate =row.claDate
          this.claInfo.startTime =row.startTime
          this.claInfo.endTime =row.endTime
          this.claInfo.status =row.status
          this.opendata = true;
          this.loadClaInfo(row.claId)

        });


    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.courseTimeId != null) {
            updateTime(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTime(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseTimeIds = row.courseTimeId || this.ids;
      this.$modal.confirm('是否确认删除排课信息编号为"' + courseTimeIds + '"的数据项？').then(function() {
        return delTime(courseTimeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/time/export', {
        ...this.queryParams
      }, `time_${new Date().getTime()}.xlsx`)
    },

    handleAttendStatusChange(attendStatus, row) {
console.log(row.everyStuLoseHour)
      console.log(attendStatus)
        if (attendStatus === '2') {
          this.studentAttendStatusForm[row.studentCourseId].stuLoseHour = 0
        } else {
          this.studentAttendStatusForm[row.studentCourseId].stuLoseHour = this.claInfo.payTotalHour

        }


    },
    // 自动设置到课状态
    handleAutoDealStudentAttendStatusInfo(attendStatus) {
      this.$nextTick(() => {
        this.chooseStudentCourseIds = []
        this.dataList.forEach(row => {
          this.chooseStudentCourseIds.push(row.studentCourseId)
          this.$refs.table.toggleRowSelection(row, true)
        })
      })
      if (attendStatus !== '3'){
      this.dataList.forEach(item => {
        this.$set(this.studentAttendStatusForm, item.studentCourseId, {
          attendStatus: attendStatus,
          stuLoseHour:  attendStatus == '1'?this.claInfo.payTotalHour
            : 0,
        })
      })}
      else {
        this.dataList.forEach(item => {
          this.$set(this.studentAttendStatusForm, item.studentCourseId, {
            attendStatus: item.attendStatus,
            stuLoseHour:  item.everyStuLoseHour,
          })
        })}

      },




    // 上课
    handleClaAttend() {

      let checkResult = true
      const studentAttendList = []
      try {
        this.dataList.forEach(item => {
          if (this.chooseStudentCourseIds.indexOf(item.studentCourseId) !== -1) {
            if (item.balanceHour < this.studentAttendStatusForm[item.studentCourseId].stuLoseHour) {
              this.msgError(item.studentName + ',课时不足,无法上课!')
              checkResult = false
              throw new Error('课时不足,无法上课!')
            }
            studentAttendList.push({
              studentId: item.studentId,
              balanceHour: item.balanceHour-this.studentAttendStatusForm[item.studentCourseId].stuLoseHour,
              attendStatus: this.studentAttendStatusForm[item.studentCourseId].attendStatus,
              studentCourseId: item.studentCourseId,
              stuLoseHour: this.studentAttendStatusForm[item.studentCourseId].stuLoseHour
            })

          }
        })
      } catch (e) {
        console.log('balance hour error')
      }

      if (!checkResult) {
        return
      }
      this.claInfo.claTimeAttendItemList = studentAttendList
      this.loading = true
      if(this.claInfo.status == '1'){
      addAttend(this.claInfo).then(response => {
        this.loading = false
        if (response.code === 200) {
          this.$emit('success')
          this.opendata = false
          this.msgSuccess('记上课成功')
          this.cancel()
          this.getList();
        } else {
          this.msgError(response.msg)
          this.getList();
        }
      }).catch(() => {
        this.loading = false
      })
    }
    else {
        updateAttend(this.claInfo).then(response => {
          this.loading = false
          if (response.code === 200) {
            this.$emit('success')
            this.opendata = false
            this.msgSuccess('记上课成功')
            this.getList();
          } else {
            this.msgError(response.msg)
            this.getList();
          }
        }).catch(() => {
          this.loading = false
        })
      }


    }

  }
};
</script>
<style lang="scss" >
// 新增form 大小
.add-form {
  .el-select .el-input {
    width: 50px;
  }
  .el-input, .el-input-number{
    width: 50px;
  }
  .auto-width .el-input{
    width: 50px;
  }
  .el-date-editor.el-input{
    width: 50px;
  }
  &.auto-width {
    .el-date-editor.el-input, .el-date-editor.el-input__inner, .el-input, .el-input-number {
      width: auto;
    }
  }
}

.auto-width {
  .el-date-editor.el-input, .el-date-editor.el-input__inner, .el-input, .el-input-number {
    width: auto;
  }}
</style>

